package com.zeratul.common.feign.inter;

import cn.hutool.core.util.ObjectUtil;
import com.zeratul.common.core.constant.RemoteConstants;
import com.zeratul.common.core.context.DataContextHolde;
import com.zeratul.common.json.utils.JsonUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.MDC;

import java.util.Map;

/**
 * 请求链路上下文传递拦截器
 * 用于在Feign请求之前，将调用方服务的链路上下文数据传递给被调用方
 */
public class ContextFeignReqInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        //获取链路上下文
        Map<String, Object> traceContext = DataContextHolde.getTraceContextOnCopy();
        if (ObjectUtil.isNotEmpty(traceContext)) {
            requestTemplate.header(RemoteConstants.TRACE_CONTEXT, JsonUtils.serialize(traceContext));
        }

        //获取MDC
        Map<String, String> mdc = MDC.getCopyOfContextMap();
        if (ObjectUtil.isNotEmpty(mdc)) {
            requestTemplate.header(RemoteConstants.MDC, JsonUtils.serialize(mdc));
        }
    }
}
